using System;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Uow;
using Volo.Abp.Settings;
using Volo.Abp.Domain.Services;
using Volo.Abp.EventBus.Distributed;
using Joy.Erp.BasicArchives.Core.Events;
using Joy.Erp.BasicArchives.Core.UniqueCodes;

namespace Joy.Erp.BasicArchives.Customers
{
    public class CustomerManager : DomainService
    {
        protected ICustomerRepository CustomerRepository => LazyServiceProvider.LazyGetRequiredService<ICustomerRepository>();
        protected IDistributedEventBus DistributedEventBus => LazyServiceProvider.LazyGetRequiredService<IDistributedEventBus>();
        protected ISettingProvider SettingProvider => LazyServiceProvider.LazyGetRequiredService<ISettingProvider>();
        protected IUniqueCodeSetter UniqueCodeSetter => LazyServiceProvider.LazyGetRequiredService<IUniqueCodeSetter>();

        [UnitOfWork]
        public async Task<Customer> CreateAsync(Customer entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            entity.SetId(GuidGenerator.Create());
            entity.TenantId = CurrentTenant.Id;

            if (entity.Code.IsNullOrWhiteSpace())
            {
                var uniqueCodeConfigration = await SettingProvider.GetOrNullAsync($"UniqueCodeConfigration:{typeof(Customer).FullName}");
                UniqueCodeSetter.SetCode(entity, uniqueCodeConfigration);
            }

            await DistributedEventBus.PublishAsync(new EntityCreatingEto<Customer>(entity), false);
            return await CustomerRepository.InsertAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task<Customer> UpdateAsync(Customer entity, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            await DistributedEventBus.PublishAsync(new EntityUpdatingEto<Customer>(entity), false);
            return await CustomerRepository.UpdateAsync(entity, autoSave, cancellationToken);
        }

        [UnitOfWork]
        public async Task DeleteAsync(Guid id, bool autoSave = false, CancellationToken cancellationToken = default)
        {
            var entity = await CustomerRepository.GetAsync(id);

            await DistributedEventBus.PublishAsync(new EntityDeletingEto<Customer>(entity), false);
            await CustomerRepository.DeleteAsync(entity, autoSave, cancellationToken);
        }
    }
}